package utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;

public class Util {
	
	/**
	 * 用map替换字符串中的参数
	 * @param sql
	 * @param argExpB
	 * @param argExpE
	 * @param argMap
	 * @return
	 */
	public static String replacWithMap(String sql, String argExpB, String argExpE, Map<String, String> argMap)
	  {
	    if (argMap == null)
	    {
	      return "";
	    }
	    if (sql != null)
	    {
	      while ((sql.indexOf(argExpB) != -1) && (sql.indexOf(argExpE) != -1))
	      {
	        String argName = sql.substring(sql.indexOf(argExpB) + argExpB.length(), sql
	          .indexOf(argExpE));

	        if ((argMap.get(argName) != null) && 
	          (!"".equals(argMap.get(argName))))
	        {
	          sql = " " + sql.substring(0, sql.indexOf(argExpB)) + 
	            (String)argMap.get(argName) + 
	            sql.substring(sql.indexOf(argExpE) + argExpE.length()) + " ";
	        }
	        else
	        {
	          sql = "";
	        }
	      }
	    }
	    return sql;
	  }
	
	/**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String readTxt(File file){
        StringBuilder sb = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
            	sb.append(s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }
	
	//导出excel
	public static void outPutExcel(String fileName,XSSFWorkbook wb,HttpServletRequest request) throws IOException{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		wb.write(baos);
		byte[] content = baos.toByteArray();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.reset();
		response.setContentType("application/x-msdownload");
		response.addHeader("Content-Disposition", "attachment; filename=\""+fileNameSolve(request,fileName)+".xlsx\"");
		ServletOutputStream outputStream = response.getOutputStream();
		outputStream.write(content, 0, content.length);
		outputStream.flush();
	}
	
	//文件下载
	public static void downLoadFile(HttpServletRequest request,HttpServletResponse response, File filePath, String newName) throws Exception {
		InputStream in = null;
		ServletOutputStream out = null;
		try {
			in = new FileInputStream(filePath);
			response.reset();
			response.setContentType("application/x-msdownload");
			newName = fileNameSolve(request,newName);
			response.addHeader("Content-Disposition", "attachment; filename=\"" + newName + "\"");
			byte[] b = new byte[100];
			int len;
			out = response.getOutputStream();
			while ((len = in.read(b)) > 0) {
				out.write(b, 0, len);
			}
			out.flush();

		} catch (Exception e) {
			response.setContentType("text/html;charset=UTF-8");
			request.setAttribute("select", "maintenanceServiceReport");
			request.getRequestDispatcher("/pages/enterprise/fileNotFound.jsp").forward(request,response);
			e.printStackTrace();
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
		
	//写入excel
	public static XSSFSheet writeExcel(XSSFSheet outPutSheet,String[] cells) throws Exception, IOException{
		XSSFRow row = outPutSheet.createRow(outPutSheet.getPhysicalNumberOfRows());
		for(int i = 0;i<cells.length;i++){
			row.createCell(i).setCellValue(new XSSFRichTextString(cells[i]));
		}
		return outPutSheet;
	}
	
	private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
	//判断浏览器是否是微软浏览器
    public static boolean isMSBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true;
        }
        return false;
    }
	//下载文件中文乱码解决
    public static String fileNameSolve(HttpServletRequest request,String beforeFileName) throws UnsupportedEncodingException{
    	boolean isMSIE = isMSBrowser(request);
		if (isMSIE) {
			beforeFileName = URLEncoder.encode(beforeFileName, "UTF-8");
        }else {
        	beforeFileName = new String(beforeFileName.getBytes("UTF-8"), "ISO-8859-1");
        }
		return beforeFileName;
    }
}
